<template>
	<view class="container">
		<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" activeColor="#0081ff"
			styleType="text" class="segment-tabs"></uni-segmented-control>
		<view class="content">
			<view v-show="current==0">
				<!-- CHZD 诊断 -->
				<detectCHZD v-if="deviceType == 'CHZD'" :deviceInfo="deviceInfo" :deviceType="deviceType"></detectCHZD>
				<detectCC v-else-if="deviceType =='CC'" :deviceInfo="deviceInfo" :deviceType="deviceType"></detectCC>
			</view>
			<view v-show="current !=0 ">
				<view class="param-contents" v-if="deviceType == 'CHZD'">
					<u-card v-for="(one ,index) in paramItems" :key="index" :title="one"
						@click="goPage(index)"></u-card>
				</view>
				<view class="param-contents" v-if="deviceType == 'CC'">
					<u-card v-for="(one ,index) in paramItems.slice(0,3)" :key="index" :title="one"
						@click="goPage2(index)"></u-card>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import detectCHZD from "./components/detectCHZD.vue";
	import detectCC from "./components/detectCC.vue";
	import {
		authPassword,
		serviceId,
		characteristicId1,
		characteristicId2,
	} from "@/utils/service.js";
	import {
		goBack,
		sendAuthString
	} from "@/utils/index.js";
	import {
		mapState,
	} from 'vuex';
	import {
		ab2hex,hexCharCodeToStr,hecToDec
	} from "@/utils/index.js";
	import {
		calculateMd5
	} from "@/utils/AesEncrypt.js";
	export default {
		components: {
			detectCHZD,
			detectCC,
		},
		data() {
			return {
				current: 0,
				items: ['诊断', '状态查询', '参数', '版本查询'],
				paramItems: [
					"主控单元", "仓控单元", "检测单元", "柜控电源单元", "整流电源单元", "充电电源", "电池单元"
				], //参数模块

				device: null,
				deviceInfo: {},

				deviceType: null, //设备类型
				binNum: 0, //仓数
			}
		},
		computed: {
			...mapState(['curConnectBLE', 'maxMTU']),
			// 柜控电源数量
			comCabinNum() {
				if (Number(this.binNum) < 24) {
					return 1;
				} else if (Number(this.binNum) >= 24 && Number(this.binNum) < 36) {
					return 2;
				} else {
					return 3;
				}
			},
			comColor() {
				return function(item) {
					if (item == 0) {
						return '#f56c6c';
					} else if (item == 1) {
						return '#19be6b'
					}
				}
			},
			comColor2() {
				return function(item) {
					if (item == 1) {
						return '#f56c6c';
					} else if (item == 0) {
						return '#19be6b'
					}
				}
			},
			detailYesOrNo() {
				return function(val) {
					if (val == 1) {
						return "是";
					} else if (val !== '' && val != 1) {
						return '否';
					} else {
						return '';
					}
				}
			},
		},
		watch: {
			'$store.state.curConnectBLE': {
				immediate: true,
				deep: true,
				handler(e) {},
			},
			'maxMTU': {
				immediate: true,
				deep: true,
				handler(e) {
					console.log('watch maxMTU值变化')
					console.log(e)
				},
			}
		},
		// 进入页面,判断设备类型;计算仓数
		async onLoad(e) {
			this.deviceInfo = JSON.parse(decodeURIComponent(e.deviceInfo));
			// 设备类型 CC:充电柜; CHZD:换电柜
			this.deviceType = (this.deviceInfo.localName && this.deviceInfo.localName.startsWith('CC') || this
					.deviceInfo.name && this.deviceInfo.name.startsWith('CC')) ?
				"CC" : 'CHZD';
			// 计算仓数
			this.binNum = this.computBInNum(this.deviceInfo.localName);

			this.watchIsConnect();
		},
		methods: {
			async watchIsConnect() {
				// 监听之前是否有其他设备连接,是,断开连接,建立新连接;否,直接建立连接.
				// 若当前设备已连接连接,则不做操作
				if (this.curConnectBLE.length == 0) {
					try {
						this.$Toast.loading('连接中~');
						await this.connect(this.deviceInfo);
						await this.doAuth();

						//协商MTU
						this.setMaxMTU(this.deviceInfo.deviceId);
					} catch (err) {
						setTimeout(() => {
							// 测试
							// goBack();
						}, 2000)

					}
				} else {
					let inx = this.curConnectBLE.findIndex(item => item.deviceId == this.deviceInfo.deviceId);
					if (inx == -1) {
						let datas = await this.$store.dispatch('closeBLEConnection', this.curConnectBLE[0].deviceId);
						if (datas) {
							this.$Toast.loading('连接中~');
							try {
								await this.connect(this.deviceInfo);
								await this.doAuth();

								// Android协商MTU
								this.setMaxMTU(this.deviceInfo.deviceId);
							} catch (err) {
								setTimeout(() => {
									// 测试
									// goBack();
								}, 2000)
							}
						}
					} else {
						await this.doAuth();
						// Android协商MTU
						this.setMaxMTU(this.deviceInfo.deviceId);
					}
				}
			},
			// 连接设备
			async connect(item) {
				try {
					await this.$store.dispatch('createBLEConnection', item);
					await this.$store.dispatch('checkDeviceService', {
						deviceId: item.deviceId,
						serviceId,
						characteristicId: characteristicId2
					})
					item.serviceId = serviceId
					item.characteristicId = characteristicId2
					this.deviceInfo = item
				} catch (err) {}
			},
			// 鉴权请求
			doAuth() {
				let that = this;
				that.$Toast.loading('鉴权中~');
				// 向蓝牙设备发送数据
				let {
					deviceId,
				} = that.deviceInfo;
				const buffer = sendAuthString(authPassword);
				console.log('这是传输的鉴权码------')
				console.log(ab2hex(buffer))
				uni.writeBLECharacteristicValue({
					deviceId,
					serviceId,
					characteristicId: characteristicId1,
					// 这里的value是ArrayBuffer类型
					value: buffer,
					success(res) {
						setTimeout(() => {
							// 此处延时,解决APP中readBLECharacteristicValue提示无法写入BLE特征值问题
							that.doAuthRead();
						}, 300)
					},
					fail(err) {
						console.log(err)
						that.$Toast.none('鉴权失败！');
						setTimeout(() => {
							// 测试
							// goBack();
						}, 2000)
					}
				})
			},
			doAuthRead() {
				let {
					deviceId,
				} = this.deviceInfo;
				let that = this;
				// 读取低功耗蓝牙设备的特征值的二进制数据值
				uni.readBLECharacteristicValue({
					deviceId,
					serviceId,
					characteristicId: characteristicId1,
					success(res) {
						uni.onBLECharacteristicValueChange(function(res) {
							uni.hideLoading();
							let value = res.value;
							// 第1字节为鉴权结果，后面6字节为毫秒时间戳，鉴权通过时，返回13位时间戳，鉴权失败时返回0
							// 0：鉴权通过
							// 1：鉴权失败
							let uint8Array = new Uint8Array(value);
							let newArray = Array.from(uint8Array);
							let hexValue = ab2hex(value);
							console.log('鉴权结果====='+hexValue)
							let strValue = hecToDec(hexValue.slice(2));
							console.log(hexValue)
							console.log('这是16进制转10进制时间戳======')
							console.log(strValue)
							let start = newArray.slice(0, 1);
							let end = newArray.slice(1);
							// 1.对鉴权成功后返回的时间戳进行一次md5的哈希处理(32位小写模式)。
							// 2.截取第1步获取的md5的后16位作为加密密钥。
							if (start == 1) {
								that.$Toast.none('鉴权失败！');
								setTimeout(() => {
									// 测试
									// goBack();
								}, 2000)
							} else if (start == 0) {
								that.$Toast.success('鉴权成功！', 1000);
								console.log('这是md5加密结果--------')
								console.log(calculateMd5(String(strValue)))
								let secretKey = calculateMd5(strValue).slice(-16);
								console.log('md5的后16位作为加密密钥=======')
								console.log(secretKey)
								// 存储加密密钥
								uni.setStorageSync('secretKey', secretKey);
							}
						})

					},
					fail(err) {
						console.log(err)
						that.$Toast.none('鉴权失败！');
						setTimeout(() => {
							// 测试
							// goBack();
						}, 2000)
					}
				})
			},
			// 协商MTU
			setMaxMTU(deviceId) {
				let that = this;
				let platform = uni.getSystemInfoSync().platform;
				switch (platform) {
					case "android":
						uni.setBLEMTU({
							deviceId: deviceId,
							mtu: 512,
							success(res) {
								console.log(res)
							},
							fail(error){
								console.log(error)
							}
						})
						// 若设置失败,会分配一个合适的MTU
						// uni.onBLEMTUChange(function(res) {
						// 	cosole.log(res)
						// 	that.$store.commit("setMaxMTU", res.mtu);
						// })
						break;
					case "ios":
						// uni.getBLEMTU({
						// 	deviceId: deviceId,
						// 	success: res => {
						// 		that.$store.commit("setMaxMTU", res.mtu);
						// 	},
						// 	fail: err => {
						// 		console.log('获取MTU失败:', err);
						// 	}
						// });
						break;
				}
			},
			// 计算仓数
			computBInNum(str) {
				const regex = /\d/;
				const match = str.match(regex);
				if (match) {
					const index = match.index;
					const result = str.substr(index, 2);
					return result;
				}
			},
			onClickItem(e) {
				if (this.current != e.currentIndex) {
					this.current = e.currentIndex;
				}
			},
			// 参数详情
			goPage(index) {
				let url;
				switch (this.current) {
					case 1:
						url = "/pagesA/bluetooth/state/index";
						break;
					case 2:
						url = "/pagesA/bluetooth/param/param";
						break;
					case 3:
						url = "/pagesA/bluetooth/version/index";
						break;
				}
				uni.navigateTo({
					url: `${url}?type=${index}&binNum=${this.binNum}&deviceInfo=${encodeURIComponent(JSON.stringify(this.deviceInfo))}`
				})
			},
			goPage2(index) {
				let url;
				switch (this.current) {
					case 1:
						url = index == 0 ? "/pagesA/bluetooth/state2/state2Detail" : "/pagesA/bluetooth/state2/index";
						break;
					case 2:
						url = "/pagesA/charge/param/param";
						break;
					case 3:
						url = "/pagesA/charge/version/index";
						break;
				}
				uni.navigateTo({
					url: `${url}?type=${index}&binNum=${this.binNum}&deviceInfo=${encodeURIComponent(JSON.stringify(this.deviceInfo))}`
				})
			},
		},
	}
</script>

<style>
	page {
		background-color: #EFF0F1 !important;
	}
</style>
<style lang="scss" scoped>
	@import "./index.scss";
</style>